﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApp.Models;
using WebApp.BLL.Manage;
using WebApp.BLL;
using WebApp.ViewModels;
using WebApp.Common;
using WebApp.Web.Core.Auth;
using Newtonsoft.Json.Linq;
using WebApp.ViewModels.Manage;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp.Areas.Manage.Controllers
{
    public class UserController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region List

        // GET: Manage/User

        [AuthorizeFilter("Manage.User")]
        public ActionResult List()
        {
            //菜单图标
            ViewBag.NavIcon = new S_menuService().GetMenuIconByAction();

            //编辑权限
            ViewBag.CanEdit = UserAuthBLL.HasAuth("Master.User.Edit");
            
            //角色列表
            ViewBag.RoleList = new SelectList(new S_roleService().List().Where(p => p.Roleid != "A0000"), "Roleid", "Rolename");

            return View();
        }

        #endregion

        #region 查询列表数据

        [AuthorizeFilter("Manage.User", ActionType.Ajax)]
        public JsonResult UserListJson(int page, int rows, string roleid, string s, string sort, string order)
        {
            S_userService userservice = new S_userService();
            S_roleService roleService = new S_roleService();

            Dictionary<string, object> result = new Dictionary<string, object>();

            int rowscount = 0;

            var list = userservice.PageList(page, rows, roleid, s, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.Username,
                p.Realname,
                p.Dept_id,
                Gender = CommonStr.GetEnumName(typeof(enmGender), Utils.NvInt(p.Sex)).ToString(),
                p.Islocked,
                Lastlogintime = p.Lastlogintime.HasValue ? p.Lastlogintime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                p.Logintimes,
                Roles = roleService.GetRoleNamesByUserid(p.Id)
            });

            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        #endregion

        #region 删除

        [AuthorizeFilter("Manage.User.Edit", ActionType.Ajax)]
        public JsonResult Delete(string ids)
        {
            try
            {
                S_userService userservice = new S_userService();

                foreach (string id in ids.Split(','))
                {
                    if (string.IsNullOrEmpty(id)) continue;

                    //逻辑删除
                    var user = userservice.Find(Convert.ToInt32(id));

                    userservice.DeleteUser(user);
                }

                return Json(new AjaxResult("0", "删除成功"));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 保存

        [ValidateInput(false)]
        [AuthorizeFilter("Manage.User.Edit", ActionType.Ajax)]
        public JsonResult Save(string json)
        {
            try
            {
                S_userService userservice = new S_userService();
                UserEditModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<UserEditModel>(json);

                //新增时初始化默认值
                S_user user = new S_user
                {
                    Isdeleted = "0",
                    Islocked = "0",
                    Ischangepwd = "1",
                    Logintimes = 0
                };

                //修改时，先从数据库查询
                if (model.User.Id > 0) user = userservice.Find(model.User.Id);
                //Model赋值
                model.User.SetModelData<S_user>(user);

                user.Usertype = "admin";

                //if (string.IsNullOrEmpty(user.Language))
                //{
                //    //默认语言
                //    var site = new Tb_siteService().Find(user.SiteId);
                //    user.Language = site.Location;
                //}

                //保存
                userservice.Save(user, model.UserRoles);

                return Json(new AjaxResult(AjaxResult.RESULT_OK, "操作成功", user.Id.ToString()));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 编辑/查看

        // GET: Manage/Role/Edit/5
        [AuthorizeFilter("Manage.User.Edit", ActionType.Ajax)]
        public ActionResult Edit(int id)
        {
            S_userService userservice = new S_userService();
            S_user_roleService userroleservice = new S_user_roleService();
            //S_departmentService deptservice = new S_departmentService();
            S_roleService roleservice = new S_roleService();
            S_dictService dict = new S_dictService();

            if (id == 0)
            {
                //注意：DropDownList的name属性和ViewBag的key值不能相同，否则会照成SelectedValue失效
                //性别下拉框
                ViewBag.GenderList = new SelectList(CommonStr.EnumToList(typeof(enmGender)), "Key", "Value");
                //角色下拉框
                //排除开发者角色
                ViewBag.RoleList = roleservice.List().Where(p => p.Roleid != "A0000").OrderBy(p => p.Roleid).Select(p => new UserRoleModel
                {
                    Roleid = p.Roleid,
                    Rolename = p.Rolename,
                    Description = p.Description,
                    Ischecked = false
                }).ToList();

                return View(new S_user());
            }
            else
            {
                S_user item = userservice.Find(id);
                if (item == null)
                {
                    throw new HttpException(404, "User(id='" + id.ToString() + "') not found!");
                }

                ViewBag.GenderList = new SelectList(CommonStr.EnumToList(typeof(enmGender)), "Key", "Value");

                //用户角色
                ViewBag.RoleList = roleservice.List().Where(p => p.Roleid != "A0000").OrderBy(p => p.Roleid).Select(p => new UserRoleModel
                {
                    Roleid = p.Roleid,
                    Rolename = p.Rolename,
                    Description = p.Description,
                    Ischecked = (userroleservice.GetByUseridAndRoleid(item.Id, p.Roleid) != null)
                }).ToList();

                return View(item);
            }
        }

        #endregion

        #region 重复验证

        [IgnoreAuthorizeFilter]
        public string ExistCheck(int id, string username)
        {
            return new S_userService().Exist(id, username) ? "no" : "yes";
        }

        #endregion

        #region 密码验证

        //密码长度验证
        [IgnoreAuthorizeFilter]
        public string PwdLengthChk(string password)
        {
            return CommonStr.CheckPasswordRule(password) == "ok" ? "yes" : "no";
        }

        #endregion

        #region  重置密码

        //[AuthorizeFilter("Manage.User.Resetpwd")]
        [AuthorizeFilter("Manage.User.Resetpwd", ActionType.Ajax)]
        public ActionResult Resetpwd(int id)
        {
            var user = new S_userService().Find(id);

            return View(user);
        }

        [AuthorizeFilter("Manage.User.Resetpwd", ActionType.Ajax)]
        [ValidateInput(false)]
        public JsonResult ChangePwd(string json)
        {
            try
            {
                string urlAddress = Request.Url.ToString();
                S_userService userService = new S_userService();
                UserEditModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<UserEditModel>(json);
                if (model.User.Id > 0)
                {
                    S_user user = userService.Find(model.User.Id);

                    if (user != null)
                    {
                        user.Password = Utils.MD5Password(model.User.Values["Password"].ToString());
                        user.Ischangepwd = model.User.Values["Ischangepwd"].ToString();
                        userService.Update(user);

                        ////短信内容
                        //S_sms_templateService smstemplateService = new BLL.Manage.S_sms_templateService();
                        //Dictionary<string, string> param = new Dictionary<string, string>();
                        //param.Add("password", model.User.Values["Password"].ToString());
                        //string MobileMessage = smstemplateService.GetSmsContent("mobile.reset.password", param);                        //发送短信
                        //SMSCommon.Sms(MobileMessage,S_smslogService.enmSmsValidatetype.重置密码.ToString(),urlAddress,user.Mobile);

                        //记录日志
                        new S_user_logService().addUserLog(enmOprtType.重置密码, SessionManage.User.Id, SessionManage.User.Username, "");
                    }
                    return Json(new AjaxResult(AjaxResult.RESULT_OK, "重置成功"));
                }
                else
                {
                    return Json(new AjaxResult(AjaxResult.RESULT_OK, "重置失败"));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 修改密码

        //[AuthorizeFilter("Manage.User.Resetpwd", ActionType.Ajax)]
        [IgnoreAuthorizeFilter]
        //[ValidateInput(false)]
        public ActionResult ChangePassword()
        {
            S_userService userService = new S_userService();
            S_user user = userService.Find(SessionManage.User.Id);

            if (user == null)
            {
                return new RedirectResult("/");
            }
            else
            {
                return View(user);
            }
        }

        [IgnoreAuthorizeFilter]
        public JsonResult SavePassword(string pwd)
        {
            try
            {
                if (Utils.NvStr(pwd) == "")
                {
                    return Json(new AjaxResult(AjaxResult.RESULT_ERROR, "请填写密码"));
                }

                S_userService userService = new S_userService();
                S_user user = userService.Find(SessionManage.User.Id);

                if (user != null)
                {
                    user.Password = Utils.MD5Password(pwd);
                    userService.Update(user);

                    //记录日志
                    new S_user_logService().addUserLog(enmOprtType.修改密码, user.Id, user.Username, "");

                    return Json(new AjaxResult(AjaxResult.RESULT_OK, "修改成功"));
                }
                else
                {
                    return Json(new AjaxResult(AjaxResult.RESULT_ERROR, "修改失败"));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 密码修改验证
        /// <summary>
        /// 界面已验证---
        /// 非空 
        /// 只含数字和字母
        /// 两次输入新密码是否一致 
        /// ----
        /// 原密码是否正确
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        [IgnoreAuthorizeFilter]
        public string PasswordChk(string oldPassword)
        {
            string result = "";
            S_userService userService = new S_userService();
            if (SessionManage.User.Id > 0)
            {
                S_user user = userService.Find(SessionManage.User.Id);
                if (user != null)
                {
                    //CommonStr str = new CommonStr();
                    //return str.CheckPasswordRule(oldPassword);
                    if (user.Password.ToUpper() != Utils.MD5Password(oldPassword).ToUpper())
                    {
                        result = "输入原密码或用户不存在！";
                    }
                    else
                    {
                        result = "ok";
                    }
                }
            }
            return result;
        }

        [IgnoreAuthorizeFilter]
        public string PasswordLengthChk(string newPassword)
        {
            return CommonStr.CheckPasswordRule(newPassword) == "ok" ? "yes" : "no";
        }

        #endregion

        #region 解锁/锁定

        [AuthorizeFilter("Manage.User.Edit", ActionType.Ajax)]
        public JsonResult Islockedpwd(int ids)
        {
            S_userService userSerice = new S_userService();
            try
            {
                S_user user = userSerice.Find(ids);
                if (user != null)
                {
                    if (user.Islocked == "1")
                    {
                        user.Islocked = "0";
                        new S_userService().Update(user);
                        new S_user_logService().addUserLog(enmOprtType.解锁, user.Id, user.Username, "");
                    }
                    else
                    {
                        user.Islocked = "1";
                        new S_userService().Update(user);
                        new S_user_logService().addUserLog(enmOprtType.锁定, user.Id, user.Username, "");
                    }

                    return Json(new AjaxResult(AjaxResult.RESULT_OK, "操作成功"));
                }
                else
                {
                    return Json(new AjaxResult(AjaxResult.RESULT_ERROR, "操作失败"));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

    }
}
